package com.groupbuying.storeinternal.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.google.common.base.Strings;

import com.groupbuying.storeinternal.connector.CoustomerFeign;
import com.groupbuying.storeinternal.connector.SettleFeign;
import com.groupbuying.storeinternal.connector.SysconfigFeign;
import com.groupbuying.storeinternal.connector.WechatAliFeign;
import com.groupbuying.storeinternal.constants.CommonConstants;
import com.groupbuying.storeinternal.constants.StoreAccountEnumConstants;
import com.groupbuying.storeinternal.constants.StoreAccountWxinfoRelEnumConstants;
import com.groupbuying.storeinternal.constants.StoreConstants;
import com.groupbuying.storeinternal.context.FilterContextHandler;
import com.groupbuying.storeinternal.dao.*;
import com.groupbuying.storeinternal.dao.forManage.StoreAccountRoleDao;
import com.groupbuying.storeinternal.dao.forManage.StoreRoleDao;
import com.groupbuying.storeinternal.dao.forManage.StoreRoleMenuDao;
import com.groupbuying.storeinternal.domain.*;
import com.groupbuying.storeinternal.domain.forManage.StoreAccountRoleDO;
import com.groupbuying.storeinternal.domain.forManage.StoreRoleDO;
import com.groupbuying.storeinternal.domain.forManage.StoreRoleMenuDO;
import com.groupbuying.storeinternal.dto.LoginDTO;
import com.groupbuying.storeinternal.dto.StoreCapitalVirtualAccountDetaiDTO;
import com.groupbuying.storeinternal.dto.forManage.AccountDTO;
import com.groupbuying.storeinternal.dto.forManage.StoreAccountDTO;
import com.groupbuying.storeinternal.dto.forManage.do2dto.AccountConvert;
import com.groupbuying.storeinternal.pojo.StoreAccountEnum;
import com.groupbuying.storeinternal.service.StoreAccountService;
import com.groupbuying.storeinternal.service.forManage.StoreMenuService;
import com.groupbuying.storeinternal.utils.*;
import com.groupbuying.storeinternal.utils.apiresult.ApiResult;
import com.groupbuying.storeinternal.vo.forManage.StoreAccountVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ywxd
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class StoreAccountServiceImpl implements StoreAccountService {

    @Autowired
    private StoreAccountWxinfoRelDao storeAccountWxinfoRelDao;
    @Autowired
    private CoustomerFeign coustomerFeign;
    @Autowired
    StoreAccountService storeAccountService;
    @Autowired
    StoreAccountDao accountMapper;
    @Autowired
    StoreAccountRoleDao accountRoleMapper;
    @Autowired
    SysconfigFeign sysconfigFeign;
    @Autowired
    StoreRoleDao storeRoleDao;
    @Autowired
    StoreRoleMenuDao storeRoleMenuDao;
    @Autowired
    StoreAccountRoleDao storeAccountRoleDao;
    @Autowired
    StoreMenuService storeMenuService;
    @Autowired
    StoreCheckoutCounterRelDao storeCheckoutCounterRelDao;
    @Autowired
    StoreAccountShopRelDao storeAccountShopRelDao;
    @Autowired
    StoreShopDao storeShopDao;
    @Autowired
    SettleFeign settleFeign;
    @Autowired
    StoreCheckoutCounterDao storeCheckoutCounterDao;
    @Autowired
    StoreCapitalVirtualAccountDao storeCapitalVirtualAccountDao;
    @Autowired
    StoreCapitalVirtualAccountDetailDao storeCapitalVirtualAccountDetailDao;
    @Autowired
    StoreMainInfoDao storeMainInfoDao;
    @Autowired
    WechatAliFeign wechatAliFeign;

    private static final Logger logger = LoggerFactory.getLogger(StoreAccountService.class);

    @Override
    public StoreAccountDO get(String id) {
        List<BigInteger> roleIds = accountRoleMapper.listRoleId(id);
        StoreAccountDO storeAccountDO = accountMapper.get(id);
        storeAccountDO.setRoleIds(roleIds);
        return storeAccountDO;
    }

    @Override
    public StoreAccountDO getByAccountName(String accountName) {
        Map map_repeat = new HashMap();
        map_repeat.put("accountName", accountName);
        List<StoreAccountDO> list_repeat = accountMapper.list(map_repeat);
        if (list_repeat.size() > 0) {
            return list_repeat.get(0);
        }
        return null;
    }

    @Override
    public StoreAccountDO getByParamsName(Map<String, Object> params) {
        List<StoreAccountDO> list_repeat = accountMapper.list(params);
        if (list_repeat.size() > 0) {
            return list_repeat.get(0);
        }
        return null;
    }

    public StoreAccountDO getByProviderName(String providerName) {
        Map map_repeat = new HashMap();
        map_repeat.put("providerName", providerName);
        List<StoreAccountDO> list_repeat = accountMapper.list(map_repeat);
        if (list_repeat.size() > 0) {
            return list_repeat.get(0);
        }
        return null;
    }

    @Override
    public List<StoreAccountDO> list(Map<String, Object> map) {
        List<StoreAccountDO> resultList = accountMapper.list(map);
        for (StoreAccountDO item : resultList) {
            //1:正常,2:待审核,3审核驳回
            if (item.getStatus().equals("1")) {
                item.setStatus("审核通过");
            } else if (item.getStatus().equals("2")) {
                item.setStatus("待审核");
            } else if (item.getStatus().equals("3")) {
                item.setStatus("审核驳回");
            }
        }
        return resultList;
    }

    @Override
    public int count(Map<String, Object> map) {
        return accountMapper.count(map);
    }

    @Override
    public int save(StoreAccountDO storeAccountDO) {

        /* 这里需要把leaf生成的唯一ID设置进去 */
        String uuid = sysconfigFeign.getUuidByLeaf();
        storeAccountDO.setAccountId(uuid);

        int count = accountMapper.save(storeAccountDO);
        String accountId = storeAccountDO.getAccountId();
        List<BigInteger> roles = storeAccountDO.getRoleIds();
        accountRoleMapper.removeByAccountId(accountId);
        List<StoreAccountRoleDO> list = new ArrayList<>();
        for (BigInteger roleId : roles) {
            StoreAccountRoleDO storeAccountRoleDO = new StoreAccountRoleDO();
            storeAccountRoleDO.setAccountId(accountId);
            storeAccountRoleDO.setRoleId(roleId);
            list.add(storeAccountRoleDO);
        }
        if (list.size() > 0) {
            accountRoleMapper.batchSave(list);
        }
        return count;
    }

    @Transactional
    @Override
    public ApiResult saveForAdmin(StoreAccountDO storeAccountDO) {
        if (Strings.isNullOrEmpty(storeAccountDO.getAccountName()) || Strings.isNullOrEmpty(storeAccountDO.getPassword()) || Strings.isNullOrEmpty(storeAccountDO.getName()) || Strings.isNullOrEmpty(storeAccountDO.getProviderName()) || Strings.isNullOrEmpty(storeAccountDO.getMobile())) {
            return ApiResult.paramIsNull();
        }

        // 创建账号
        String uuid = sysconfigFeign.getStoreAcountByLeaf();
        String pro = sysconfigFeign.getStoreProviderByLeaf();
        storeAccountDO.setAccountId(uuid);
        storeAccountDO.setAccountNo(sysconfigFeign.getUuidByLeaf());
        storeAccountDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
        storeAccountDO.setStatus(CommonConstants.COMMON_STATE_UES);
        storeAccountDO.setProviderId(pro);
        storeAccountDO.setProviderType(StoreConstants.STORE_MAIN_ACCOUNT);
        storeAccountDO.setAgentId(CommonConstants.COMMON_AGENT_ID);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = sdf.format(date);
        storeAccountDO.setCreateOpeTime(createdate);
        storeAccountDO.setFreezestatus(CommonConstants.COMMON_FREEZESTATUS);
        storeAccountDO.setPassword(MD5Utils.encrypt(storeAccountDO.getAccountName(), storeAccountDO.getPassword()));
        //平台注册服务商时默认代理商是平台最高权限代理商，id为00000
        String agentId = "00000";
        Map<String, Object> storeAccountParams = new HashMap();
        storeAccountParams.put("providerName", storeAccountDO.getProviderName());
        storeAccountParams.put("agentId", agentId);
        StoreAccountDO storeAccountDOExit = this.getByParamsName(storeAccountParams);

        if (storeAccountDOExit != null) {
            logger.info("StoreAccountServiceImpl-->saveForAdmin 服务商名称已存在 " + storeAccountDOExit);
            return ApiResult.failure(0, "服务商名称已存在");
        }

        StoreAccountDO storeAccountDO_exit = this.getByAccountName(storeAccountDO.getAccountName());
        if (storeAccountDO_exit != null) {
            return ApiResult.failure(0,"登录账号已存在");
        }

//        StoreAccountDO storeAccountDO_pro = this.getByProviderName(storeAccountDO.getProviderName());
//        if (storeAccountDO_pro != null) {
//            return ApiResult.failure(0,"服务商名称已存在");
//        }

        int count_account = accountMapper.save(storeAccountDO);

        // 建立总经理角色
        StoreRoleDO storeRoleDO = new StoreRoleDO();
        storeRoleDO.setRoleName(StoreAccountEnum.STORE_ADMIN_TITLE);
        storeRoleDO.setRoleSign(StoreAccountEnum.STORE_ADMIN_REMARK);
        storeRoleDO.setProviderId(storeAccountDO.getProviderId());
        int count_role = storeRoleDao.save(storeRoleDO);

        // 建立收银员角色
        StoreRoleDO storeRoleDO_shouyin = new StoreRoleDO();
        storeRoleDO_shouyin.setRoleName(StoreAccountEnum.STORE_SHOUYIN_TITLE);
        storeRoleDO_shouyin.setRoleSign(StoreAccountEnum.STORE_SHOUYIN_REMARK);
        storeRoleDO_shouyin.setProviderId(storeAccountDO.getProviderId());
        storeRoleDao.save(storeRoleDO_shouyin);

        // 角色关联权限，关联两个角色，管理员与收银员
        List<StoreRoleMenuDO> list = new ArrayList<>();
        Map roleBest = new HashMap();
        roleBest.put("roleId", StoreAccountEnum.STORE_ADMIN_ID);
        List<StoreRoleMenuDO> list_role = storeRoleMenuDao.list(roleBest);
        for (StoreRoleMenuDO role : list_role) {
            StoreRoleMenuDO storeRoleMenuDO = new StoreRoleMenuDO();
            storeRoleMenuDO.setRoleId(storeRoleDO.getRoleId());
            storeRoleMenuDO.setMenuId(role.getMenuId());
            list.add(storeRoleMenuDO);
        }

        Map roleShouyin = new HashMap();
        roleShouyin.put("roleId", StoreAccountEnum.STORE_SHOUYIN_ID);
        List<StoreRoleMenuDO> list_role_shouyin = storeRoleMenuDao.list(roleShouyin);
        for (StoreRoleMenuDO role : list_role_shouyin) {
            StoreRoleMenuDO storeRoleMenuDO = new StoreRoleMenuDO();
            storeRoleMenuDO.setRoleId(storeRoleDO.getRoleId());
            storeRoleMenuDO.setMenuId(role.getMenuId());
            list.add(storeRoleMenuDO);
        }

        if (list.size() > 0) {
            storeRoleMenuDao.batchSave(list);
        }

        // 账号关联总经理角色
        StoreAccountRoleDO storeAccountRoleDO = new StoreAccountRoleDO();
        //storeAccountRoleDO.setId(sysconfigFeign.getUuidByLeaf());
        storeAccountRoleDO.setAccountId(storeAccountDO.getAccountId());
        storeAccountRoleDO.setRoleId(storeRoleDO.getRoleId());
        int count_store = storeAccountRoleDao.save(storeAccountRoleDO);

        if (count_account > 0 && count_role > 0 && count_store > 0) {
            return ApiResult.success();
        }

        return ApiResult.failure();
    }

    @Override
    public int update(StoreAccountDO storeAccountDO) {
        int r = accountMapper.update(storeAccountDO);
        String accountId = storeAccountDO.getAccountId();
        List<BigInteger> roles = storeAccountDO.getRoleIds();
        if (null != roles) {
            accountRoleMapper.removeByAccountId(accountId);
            List<StoreAccountRoleDO> list = new ArrayList<>();
            for (BigInteger roleId : roles) {
                StoreAccountRoleDO storeAccountRoleDO = new StoreAccountRoleDO();
                storeAccountRoleDO.setAccountId(accountId);
                storeAccountRoleDO.setRoleId(roleId);
                list.add(storeAccountRoleDO);
            }
            if (list.size() > 0) {
                accountRoleMapper.batchSave(list);
            }
        }
        return r;
    }

    @Override
    public int remove(String accountId) {
        // TODO: 删除操作
        // 删除权限
        //
        // 删除角色
        //storeRoleDao.roleIdsByAccountId()
        // 删除角色与账号关联
        accountRoleMapper.removeByAccountId(accountId);
        // 删除账号
        return accountMapper.remove(accountId);
    }

    @Override
    public boolean exits(Map<String, Object> params) {
        boolean exits = accountMapper.list(params).size() > 0;
        return exits;
    }

    @Override
    public Set<String> listRoles(String userId) {
        return null;
    }

    @Override
    public int resetPwd(StoreAccountVO storeAccountVO, StoreAccountDO storeAccountDO) throws Exception {
        if (Objects.equals(storeAccountVO.getStoreAccountDO().getAccountId(), storeAccountDO.getAccountId())) {
            if (Objects.equals(MD5Utils.encrypt(storeAccountDO.getAccountName(), storeAccountVO.getPwdOld()), storeAccountDO.getPassword())) {
                storeAccountDO.setPassword(MD5Utils.encrypt(storeAccountDO.getAccountName(), storeAccountVO.getPwdNew()));
                return accountMapper.update(storeAccountDO);
            } else {
                throw new Exception("输入的旧密码有误！");
            }
        } else {
            throw new Exception("你修改的不是你登录的账号！");
        }
    }

    @Override
    public int adminResetPwd(StoreAccountVO storeAccountVO) throws Exception {
        StoreAccountDO StoreAccountDO = get(storeAccountVO.getStoreAccountDO().getAccountId());
        if ("admin".equals(StoreAccountDO.getAccountName())) {
            throw new Exception("超级管理员的账号不允许直接重置！");
        }
        StoreAccountDO.setPassword(MD5Utils.encrypt(StoreAccountDO.getAccountName(), storeAccountVO.getPwdNew()));
        return accountMapper.update(StoreAccountDO);


    }

    @Transactional
    @Override
    public int batchRemove(String[] userIds) {
        int count = accountMapper.batchRemove(userIds);
        accountRoleMapper.batchRemoveByAccountId(userIds);
        return count;
    }

    @Override
    public int updatePersonal(StoreAccountDO StoreAccountDO) {
        return accountMapper.update(StoreAccountDO);
    }

    @Override
    public Map<String, Object> updatePersonalImg(MultipartFile file, String avatar_data, Long userId) throws Exception {
        return null;
    }

    @Override
    public Map<String, StoreAccountDO> getMapByUuids(List<String> accountUuids) {

        Map<String, StoreAccountDO> map = new HashMap<String, StoreAccountDO>();
        if (accountUuids == null || accountUuids.size() <= 0) {
            return map;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("accountIds", accountUuids);
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);

        List<StoreAccountDO> list = accountMapper.getListByUuids(params);
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            list.forEach(m -> {
                map.put(m.getAccountId(), m);
            });
        }

        return map;
    }


    @Override
    public R internal_login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername().trim();
        String password = loginDTO.getPwd().trim();
        password = MD5Utils.encrypt(username, password);
        StoreAccountDO accountDO = this.getByAccountName(username);
      logger.info("该账号的详细信息,该账号的状态:{},{}",accountDO,accountDO.getFreezestatus());
        if (null == accountDO) {
            return R.error("该用户不存在");
        }
        if(("1").equals(accountDO.getFreezestatus())){
            return  R.error("该账号已冻结");
        }
        if (!accountDO.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        String agentId = accountDO.getAgentId();

        String status = accountDO.getStatus();
        if (!"00000".equals(agentId)) {
            if (!StoreAccountEnumConstants.ENUM_STATUS_NORMAL.equals(status)) {
                return R.error("服务商未审核通过");
            }
        }

        UserToken userToken = new UserToken(accountDO.getAccountName(), accountDO.getAccountId(), accountDO.getProviderId(), accountDO.getAgentId());

        String token = "";
        try {
            token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 首先清除用户缓存权限
        // menuService.clearCache(userDO.getAccountId());
        // String token = tokenService.createToken(userDO.getUserId());

        return R.ok("登录成功")
                .put("token", token)
                .put("perms", storeMenuService.PermsByUserId(accountDO.getAccountId()))
                .put("router", storeMenuService.RouterDTOsByUserId(accountDO.getAccountId()));
    }


    @Override
    public R internal_getStaffList(Map<String, Object> params) {
        try {
            params.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
            params.put("status", CommonConstants.COMMON_STATE_UES);
            params.put("providerId", FilterContextHandler.getName());
            Query query = new Query(params);
            List<AccountDTO> userDTOS = AccountConvert.MAPPER.dos2dtos((this.list(query)));

            for (AccountDTO accountDTO : userDTOS) {
                List<BigInteger> roleIds = storeAccountRoleDao.listRoleId(accountDTO.getAccountId());
                StoreRoleDO storeRoleDO = storeRoleDao.get(roleIds.get(0));
                accountDTO.setRoleName(storeRoleDO.getRoleName());
            }
            int total = userDTOS.size();
            PageUtils pageUtil = new PageUtils(userDTOS, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

    @Override
    public R internal_getStaffList_unBangDing(Map<String, Object> params) {
        try {
            params.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
            params.put("status", CommonConstants.COMMON_STATE_UES);
            params.put("providerId", FilterContextHandler.getName());
            Query query = new Query(params);
            List<AccountDTO> userDTOS = AccountConvert.MAPPER.dos2dtos((this.list(query)));
            List<AccountDTO> result_dto = new ArrayList<>();
            for (int i = 0; i < userDTOS.size(); i++) {
                AccountDTO accountDTO = userDTOS.get(i);
                List<StoreCheckoutCounterRelDO> relList = storeCheckoutCounterRelDao.getByAccount(accountDTO.getAccountId());
                if (relList.size() == 0) {
                    //已经关联收银台的不展示
                    result_dto.add(accountDTO);
                }
            }

            int total = userDTOS.size();
            PageUtils pageUtil = new PageUtils(result_dto, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

    /**
     * 服务商添加员工
     **/

    @Transactional
    @Override
    public R internal_saveStaff(StoreAccountDO storeAccountDO) {
        try {
            // 创建账号
            storeAccountDO.setAccountId(sysconfigFeign.getStoreAcountByLeaf());
            storeAccountDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
            storeAccountDO.setStatus(StoreConstants.COMMON_STATE_UES);
            storeAccountDO.setProviderId(FilterContextHandler.getName());
            storeAccountDO.setPassword(MD5Utils.encrypt(storeAccountDO.getAccountName(), storeAccountDO.getPassword()));
            storeAccountDO.setProviderType(StoreConstants.STORE_STAFF_ACCOUNT);
            storeAccountDO.setAccountNo(sysconfigFeign.getUuidByLeaf());
            storeAccountDO.setAgentId(FilterContextHandler.getAgentId());

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createdate = sdf.format(date);

            storeAccountDO.setCreateOpeTime(createdate);
            //平台注册服务商时默认代理商是平台最高权限代理商，id为00000
            String agentId = "00000";
            Map<String, String> storeAccountParams = new HashMap();
            storeAccountParams.put("accountName", storeAccountDO.getAccountName());
            storeAccountParams.put("agentId", agentId);
            StoreAccountDO storeAccountDO_exit = this.getByAccountName(storeAccountDO.getAccountName());
            if (storeAccountDO_exit != null) {
                return R.error("该账号已存在");
            }
            accountMapper.save(storeAccountDO);

            // 保存角色
            StoreAccountRoleDO storeAccountRoleDO = new StoreAccountRoleDO();
//            storeAccountRoleDO.setId(sysconfigFeign.getUuidByLeaf());
            storeAccountRoleDO.setAccountId(storeAccountDO.getAccountId());
            storeAccountRoleDO.setRoleId(storeAccountDO.getRoleIds().get(0));
            accountRoleMapper.save(storeAccountRoleDO);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @Override
    public ApiResult getByAccountId() {

        StoreAccountDO storeAccountDO = null;
        StoreAccountRoleDO storeAccountRoleDO = null;
        StoreRoleDO storeRoleDO = null;
        String username = FilterContextHandler.getUsername();
        if (username != null) {
            storeAccountDO = this.getByAccountName(username);
        }
        String accountId = FilterContextHandler.getUserID();
        if (accountId != null) {
            storeAccountRoleDO = storeAccountRoleDao.getByAccountId(accountId);
        }
        if (storeAccountRoleDO != null) {

            storeRoleDO = storeRoleDao.get(storeAccountRoleDO.getRoleId());
        }
        List<StoreCheckoutCounterRelDO> storeCheckoutCounterRel = storeCheckoutCounterRelDao.getByAccount(accountId);
        List counterUuidList = new ArrayList();
        String counterUuid = null;
        if (storeCheckoutCounterRel != null) {
            for (StoreCheckoutCounterRelDO rel : storeCheckoutCounterRel) {
                counterUuid = rel.getCounteruuid();
                counterUuidList.add(counterUuid);
            }

        }
        if (counterUuidList.size() == 0 && counterUuidList == null) {
            ApiResult.failure("counterId 不能为空");
        }
        Map map = new HashMap();
        map.put("StoreAccount", storeAccountDO);
        map.put("StoreRoleDO", storeRoleDO);
        map.put("counterUuidList", counterUuidList);
        return ApiResult.success(map);
    }


    @Override
    public ApiResult loginForStore(Map<String, Object> param) {
        logger.info("===============START===========商户登录开始===========");
        Object temp = param.get("username");
        String username = temp == null ? "" : temp.toString();
        temp = param.get("pwd");
        String pwd = temp == null ? "" : temp.toString();
        //不再校验code
        temp = param.get("code");
        String code = temp == null ? "" : temp.toString();
        //部分传openId
        temp = param.get("openId");
        String openId = temp == null ? "" : temp.toString();

        String password = MD5Utils.encrypt(username, pwd);
        StoreAccountDO accountDO = this.getByAccountName(username);

        if (null == accountDO) {
            return ApiResult.failure("该用户不存在");
        }

        if (!accountDO.getPassword().equals(password)) {
            return ApiResult.failure("密码错误");
        }
        if(("1").equals(accountDO.getFreezestatus())){
            return ApiResult.failure("该账号已冻结");
        }

        logger.info("账户I:{},{},{}", accountDO.getAccountId(), accountDO.getAccountName(), accountDO.getAccountNo());

        if(code != null && !code.equals("")){
            //获取公众号的OpenId
            Map<String,Object> resOpenId = wechatAliFeign.getMPOpenidByCode(code,"youdianproductor");
            openId = resOpenId.get("openid")==null?null:resOpenId.get("openid").toString();
            //String openId = coustomerFeign.getOpenidByCode(code);
            logger.info("用户获取openId:{}", openId);
            if (StringUtils.isEmpty(openId)) {
                logger.error("用户：{}登陆成功,code：{},openId获取失败", accountDO.getAccountId(), code);
                //return ApiResult.failure("openId获取失败");
            }
        }
        
        StoreAccountWxinfoRelDO storeAccountWxinfoRelDO = storeAccountWxinfoRelDao.getByAccountAndOpen(accountDO.getAccountId(), openId);
        StoreAccountWxinfoRelDO storeAccountWxinfoRel = new StoreAccountWxinfoRelDO();
        try {
            //openid不为空则创建微信关系
            if (storeAccountWxinfoRelDO == null && !StringUtils.isEmpty(openId)) {
                storeAccountWxinfoRel.setAccountId(accountDO.getAccountId());
                storeAccountWxinfoRel.setOpenId(openId);
                storeAccountWxinfoRel.setGmtCreate(new Date());
                storeAccountWxinfoRel.setGmtModified(new Date());
                storeAccountWxinfoRel.setIsDelete(StoreAccountWxinfoRelEnumConstants.ENUM_ISDELETE_UNDEL);
                storeAccountWxinfoRelDao.save(storeAccountWxinfoRel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        UserToken userToken = new UserToken(accountDO.getAccountName(), accountDO.getAccountId(), accountDO.getProviderId(), accountDO.getAgentId());

        String token = "";
        try {
            token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("openId", openId);
        map.put("token", token);
        map.put("perms", storeMenuService.PermsByUserId(accountDO.getAccountId()));
        map.put("router", storeMenuService.RouterDTOsByUserId(accountDO.getAccountId()));

        return ApiResult.success(map);
    }

    @Override
    public ApiResult getUshop() {
        //String accountId = params.get("accountId").toString();
        String accountId = FilterContextHandler.getUserID();
        StoreCheckoutCounterRelDO storeCheckoutCounterRelDO = null;
        StoreShopDO storeShop = null;
        String checkstandId = null;
        String storeuuid = null;
        if (StringUtils.isEmpty(accountId)) {
            logger.error("账户ID获取失败");
            return ApiResult.failure("账户ID获取失败");

        }
        storeCheckoutCounterRelDO = storeCheckoutCounterRelDao.getUshop(accountId);
        if (storeCheckoutCounterRelDO == null) {
            logger.error("收银台商户关联表获取失败");
            return ApiResult.failure("收银台商户关联表获取失败");
        }
        checkstandId = storeCheckoutCounterRelDO.getCounteruuid();
        StoreCheckoutCounterDO storeCheckoutCounterDO = storeCheckoutCounterDao.get(checkstandId);
        if (storeCheckoutCounterDO == null) {
            logger.error("收银台查询失败");
            return ApiResult.failure("收银台查询失败");
        }
        storeuuid = storeCheckoutCounterDO.getStoreuuid();
        storeShop = storeShopDao.getStoreShop(storeuuid);
        logger.info("商户ID:{},收银台ID{}", storeuuid, checkstandId);

        Date date = new Date();
        long time = date.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(calendar.getTime());
        logger.info("日期为" + format);
        Map<String, Object> map = new HashMap();
        BigDecimal flowStore = storeCapitalVirtualAccountDao.getByStorUUid(storeuuid);
        BigDecimal storeTodayFlow = settleFeign.getStoreTodayIncomeByCheckstandId(checkstandId);
        map.put("storeTodayFlow", storeTodayFlow);
        map.put("virtualaccount", flowStore);
        map.put("storeShop", storeShop);
        return ApiResult.success(map);
    }

    @Override
    public ApiResult getFlowStore(Map<String, String> map) {
        String parStart = map.get("gmtCreateStart");
        String parEnd = map.get("gmtCreateEnd");
        String checkstandId = null;
        String storeUuid = null;
        String accountId = FilterContextHandler.getUserID();

        StoreCheckoutCounterRelDO storeCheckoutCounterRelDO = storeCheckoutCounterRelDao.getUshop(accountId);
        if (storeCheckoutCounterRelDO != null) {
            checkstandId = storeCheckoutCounterRelDO.getCounteruuid();
        }
        logger.info("收银台ID" + checkstandId);
        StoreCheckoutCounterDO storeCheckoutCounterDO = storeCheckoutCounterDao.get(checkstandId);
        if (storeCheckoutCounterDO != null) {
            storeUuid = storeCheckoutCounterDO.getStoreuuid();

        }
        Map<String, Object> queryMap = new HashMap<>();
        if (!StringUtils.isEmpty(parStart) && !StringUtils.isEmpty(parEnd)) {
            //格式化开始时间
            parStart = DateUtils.format(new Date(Long.valueOf(parStart)), DateUtils.YMD);
            //传入的结束时间增加一天用于between查询的后开问题
            parEnd = DateUtils.format(new Date(Long.valueOf(parEnd) + 24 * 60 * 60 * 1000), DateUtils.YMD);
            queryMap.put("gmtCreateStart", parStart);
            queryMap.put("gmtCreateEnd", parEnd);
        }
        String[] inOrOut = {"0", "1","3"};

        queryMap.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        queryMap.put("storeUuid", storeUuid);
        queryMap.put("inOrOut", inOrOut);
        queryMap.put("page",map.get("page"));
        queryMap.put("limit",map.get("limit"));
        Query query = new Query(queryMap);

        List<StoreCapitalVirtualAccountDetaiDTO> storeCapitalVirtualAccountDetail = new ArrayList<>();
        List<StoreCapitalVirtualAccountDetailDO> storeCapitalVirtualAccountDetailList = storeCapitalVirtualAccountDetailDao.getStoreFlowListByStoreUuid(query);
        StoreCapitalVirtualAccountDetaiDTO dto = null;
        for (StoreCapitalVirtualAccountDetailDO store : storeCapitalVirtualAccountDetailList) {
            dto = new StoreCapitalVirtualAccountDetaiDTO(store);
            storeCapitalVirtualAccountDetail.add(dto);
        }


        int total = storeCapitalVirtualAccountDetailDao.countForFlow(query);
        PageUtils pageUtils = new PageUtils(storeCapitalVirtualAccountDetail, total);
        return ApiResult.success(pageUtils);
    }

    @Override
    public ApiResult getFlowStoreWithoutTime() {
        Map map = new HashMap();
        map.put("flowType", "0");
        map.put("isDelete", "1");
        ApiResult storeTodayFlowByCheckstandId = settleFeign.getStoreTodayFlowByCheckstandId(map);
        return ApiResult.success(storeTodayFlowByCheckstandId.getResult());
    }

    @Override
    public ApiResult changeUserPassword(Map<String, Object> mapParams) {
        // 解析map参数
        Object tempParam = mapParams.get("password");
        String password = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("passwordAgain");
        String passwordAgain = tempParam == null ? null : tempParam.toString();
        if (Strings.isNullOrEmpty(password) || Strings.isNullOrEmpty(passwordAgain)) {
            return ApiResult.paramIsNull();
        }
        if (!password.equals(passwordAgain)) {
            return ApiResult.failure();
        }
        String userid = FilterContextHandler.getUserID();
        StoreAccountDO storeAccountDO = this.get(userid);
        if (storeAccountDO == null) {
            return ApiResult.failure("该用户不存在");
        }

        storeAccountDO.setPassword(MD5Utils.encrypt(storeAccountDO.getAccountName(), password));
        this.update(storeAccountDO);
        return ApiResult.success();
    }

    @Override
    public List<StoreAccountDTO> getStoreAndAgentName(Map<String, Object> map) {
        List<StoreAccountDTO> resultList = accountMapper.getStoreAndAgentName(map);
        logger.info("返回的信息是：{}",resultList);
        return resultList;

    }

    @Override
    public R updateFreezeStatus(Map<String,Object> map) {
        int i = accountMapper.updateByProviderId(map);
        String providerId = map.get("providerId").toString();
        String freezestatus = map.get("freezestatus").toString();
        Map<String,Object> param = new HashMap<>();
        param.put("chainstoresuuid",providerId);
        param.put("freezestatus",freezestatus);
        int r = storeMainInfoDao.updateByChainStoresUuid(param);
        logger.info("门店表修改为:{}",r);

        logger.info("修改的状态为:{}",i);
        if(i>=0){
            return R.ok();
        }else{
            return  R.error();
        }

    }

    @Override
    public int countForMinList(Map<String, Object> map) {
        return accountMapper.countForMinList(map);
    }

}
